//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package event_dao

import (
	"context"
	"fmt"
	"time"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/external_events_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type SourceUserInfoDbItem struct {
	SourceUserId      string `bson:"_id"`
	SourceUserName    string `bson:"sourceUserName"`
	SourceDisplayName string `bson:"sourceDisplayName"`
	EventSourceId     string `bson:"eventSourceId"`
	ProjectId         string `bson:"projectId"`
	UserPolicy        int32  `bson:"userPolicy"`
	MapUserId         string `bson:"mapUserId"`
	CreateTime        int64  `bson:"createTime"`
	UpdateTime        int64  `bson:"updateTime"`
	TotalEventCount   uint32 `bson:"totalEventCount"`
}

func (item *SourceUserInfoDbItem) ToSourceUserInfo(displayName string) *external_events_api.SourceUserInfo {
	return &external_events_api.SourceUserInfo{
		SourceUserName:     item.SourceUserName,
		SourceDisplayName:  item.SourceDisplayName,
		EventSourceId:      item.EventSourceId,
		UserPolicy:         external_events_api.SOURCE_USER_POLICY(item.UserPolicy),
		MapUserId:          item.MapUserId,
		TotalEventCount:    item.TotalEventCount,
		MapUserDisplayName: displayName,
	}
}

type _SourceUserDao struct {
	mc *mongo.Collection
}

func newSourceUserDao(db *mongo.Database) (*_SourceUserDao, error) {
	mc := db.Collection(db_ns.DB_NS_EVENT + "source_user")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}, {"eventSourceId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_SourceUserDao{mc: mc}, nil
}

func (db *_SourceUserDao) List(ctx context.Context, projectId, eventSourceId string) ([]*SourceUserInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "eventSourceId": eventSourceId}, options.Find().SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*SourceUserInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_SourceUserDao) SetPolicy(ctx context.Context, projectId, eventSourceId, sourceUserName string, userPolicy int32, mapUserId string) error {
	sourceUserId := db.genSourceUserId(eventSourceId, sourceUserName)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": sourceUserId, "projectId": projectId},
		bson.M{"$set": bson.M{"userPolicy": userPolicy, "mapUserId": mapUserId, "updateTime": time.Now().UnixNano() / 1e6}})
	return err
}

func (db *_SourceUserDao) genSourceUserId(eventSourceId, sourceUserName string) string {
	return fmt.Sprintf("%s:%s", eventSourceId, sourceUserName)
}

func (db *_SourceUserDao) RemoveByEventSource(ctx context.Context, projectId, eventSourceId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"projectId": projectId, "eventSourceId": eventSourceId})
	return err
}

func (db *_SourceUserDao) Get(ctx context.Context, projectId, eventSourceId, sourceUserName string) (*SourceUserInfoDbItem, error) {
	sourceUserId := db.genSourceUserId(eventSourceId, sourceUserName)
	retItem := &SourceUserInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": sourceUserId, "projectId": projectId}).Decode(retItem)
	return retItem, err
}

func (db *_SourceUserDao) Exist(ctx context.Context, projectId, eventSourceId, sourceUserName string) (bool, error) {
	sourceUserId := db.genSourceUserId(eventSourceId, sourceUserName)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": sourceUserId, "projectId": projectId})
	return count > 0, err
}

func (db *_SourceUserDao) Insert(ctx context.Context, dbItem *SourceUserInfoDbItem) error {
	dbItem.SourceUserId = db.genSourceUserId(dbItem.EventSourceId, dbItem.SourceUserName)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_SourceUserDao) IncCount(ctx context.Context, projectId, eventSourceId, sourceUserName string) error {
	sourceUserId := db.genSourceUserId(eventSourceId, sourceUserName)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": sourceUserId, "projectId": projectId}, bson.M{"$inc": bson.M{"totalEventCount": 1}})
	return err
}
